//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { NodeEditPanelProps } from './common';
import { Button, Card, Form, Input, List, message, Popover, Select, Space } from 'antd';
import { useRoadmapStores } from '../../store';
import { Compact as CompactPicker } from '@uiw/react-color';
import type { ExtraLinkItem } from "@/api/roadmap_content";
import { EXTRA_LINK_ARTICLE, EXTRA_LINK_COURSE, EXTRA_LINK_TEST, EXTRA_LINK_VIDEO, EXTRA_LINK_WEBSITE, LEARN_POLICY_EXTRA, LEARN_POLICY_NONE, LEARN_POLICY_OPTION, LEARN_POLICY_RECOMMEND, update_node_data } from "@/api/roadmap_content";
import { request } from '@/utils/request';
import { useCommonEditor } from '@/components/Editor';
import { FILE_OWNER_TYPE_ROADMAP, GLOBAL_GROW_CENTER_FS_ID } from '@/api/fs';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { uniqId } from '@/utils/utils';

const TopicNodeEditPanel = (props: NodeEditPanelProps) => {
    const roadmapStore = useRoadmapStores();

    const [title, setTitle] = useState("");
    const [fontSize, setFontSize] = useState(14);
    const [fontWeight, setFontWeight] = useState(500);
    const [fontColor, setFontColor] = useState("black");
    const [bgColor, setBgColor] = useState("white");
    const [learnPolicy, setLearnPolicy] = useState(LEARN_POLICY_NONE);
    const [linkList, setLinkList] = useState<ExtraLinkItem[]>([]);

    const { editor, editorRef } = useCommonEditor({
        content: "",
        fsId: GLOBAL_GROW_CENTER_FS_ID,
        ownerType: FILE_OWNER_TYPE_ROADMAP,
        ownerId: roadmapStore.roadmapId,
        historyInToolbar: false,
        clipboardInToolbar: false,
        commonInToolbar: true,
        pubResInToolbar: true,
    });

    const reset = () => {
        const curNode = roadmapStore.getNode(props.nodeId);
        if (curNode == undefined) {
            return;
        }
        setTitle(curNode.basic_info.node_data.TopicData?.title ?? "");
        setFontSize(curNode.basic_info.node_data.TopicData?.font_size ?? 14);
        setFontWeight(curNode.basic_info.node_data.TopicData?.font_weight ?? 500);
        setFontColor(curNode.basic_info.node_data.TopicData?.font_color ?? "black");
        setBgColor(curNode.basic_info.node_data.TopicData?.bg_color ?? "white");
        setLearnPolicy(curNode.basic_info.node_data.TopicData?.learn_policy ?? LEARN_POLICY_NONE);
        setLinkList(curNode.basic_info.node_data.TopicData?.link_list ?? []);

        editorRef.current?.setContent(curNode.basic_info.node_data.TopicData?.content ?? "");
    };

    const updateNode = async (close: boolean) => {
        const content = editorRef.current?.getContent() ?? { type: "doc" };
        await request(update_node_data({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            node_id: props.nodeId,
            node_data: {
                TopicData: {
                    font_size: fontSize,
                    font_weight: fontWeight,
                    font_color: fontColor,
                    title: title,
                    bg_color: bgColor,
                    content: JSON.stringify(content),
                    learn_policy: learnPolicy,
                    link_list: linkList,
                },
            },
        }));
        await roadmapStore.onUpdateNode(props.nodeId);
        await reset();
        message.info("更新成功");
        if (close) {
            roadmapStore.selectNodeId = "";
        }
    };

    useEffect(() => {
        reset();
    }, []);

    return (
        <div>
            <Button type='primary' danger
                style={{ position: "fixed", top: "10px", right: "20px" }} icon={<DeleteOutlined />}
                onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    roadmapStore.removeNode(props.nodeId);
                }}>删除</Button>
            <div className='_roadmapContext'>
                {editor}
            </div>
            <Form labelCol={{ span: 4 }} style={{ marginTop: "10px" }}>
                <Form.Item label="标题">
                    <Input value={title} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setTitle(e.target.value.trim());
                    }} />
                </Form.Item>
                <Form.Item label="字体大小">
                    <Select value={fontSize} onChange={value => {
                        setFontSize(value);
                    }}>
                        {[10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50].map(item => (
                            <Select.Option key={item} value={item}>{item}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="字体颜色">
                    <Popover trigger="click" placement="bottom" content={
                        <CompactPicker color={fontColor} onChange={value => {
                            setFontColor(value.hex);
                        }} />
                    }>
                        <div style={{ backgroundColor: fontColor, width: "20px", height: "20px", cursor: "pointer", border: "1px solid grey" }} />
                    </Popover>
                </Form.Item>
                <Form.Item label="字体权重">
                    <Select value={fontWeight} onChange={value => {
                        setFontWeight(value);
                    }}>
                        {[100, 200, 300, 400, 500, 600, 700, 800, 900].map(item => (
                            <Select.Option key={item} value={item}>{item}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="背景颜色">
                    <Popover trigger="click" placement="bottom" content={
                        <CompactPicker color={bgColor} onChange={value => {
                            setBgColor(value.hex);
                        }} />
                    }>
                        <div style={{ backgroundColor: bgColor, width: "20px", height: "20px", cursor: "pointer", border: "1px solid grey" }} />
                    </Popover>
                </Form.Item>
                <Form.Item label="学习策略">
                    <Select value={learnPolicy} onChange={value => setLearnPolicy(value)}>
                        <Select.Option value={LEARN_POLICY_NONE}>未设置</Select.Option>
                        <Select.Option value={LEARN_POLICY_RECOMMEND}>推荐学习</Select.Option>
                        <Select.Option value={LEARN_POLICY_OPTION}>可选学习</Select.Option>
                        <Select.Option value={LEARN_POLICY_EXTRA}>进阶学习</Select.Option>
                    </Select>
                </Form.Item>
                <Card title="额外链接" bordered={false}
                    headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#fafafa" }}
                    extra={
                        <Button type="link" icon={<PlusOutlined style={{ fontSize: "20px" }} />} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const tmpList = linkList.slice();
                            tmpList.unshift({
                                link_id: uniqId(),
                                link_type: EXTRA_LINK_WEBSITE,
                                link_title: "",
                                link_url: "https://",
                            });
                            setLinkList(tmpList);
                        }} />
                    }>
                    <List rowKey="link_id" dataSource={linkList} pagination={false}
                        renderItem={linkItem => (
                            <List.Item extra={
                                <Button type="link" danger icon={<DeleteOutlined />} style={{ minWidth: "0px", padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        const tmpList = linkList.filter(item => item.link_id != linkItem.link_id);
                                        setLinkList(tmpList);
                                    }} />
                            }>
                                <Form layout='inline'>
                                    <Form.Item>
                                        <Select value={linkItem.link_type} onChange={value => {
                                            const tmpList = linkList.slice();
                                            const index = tmpList.findIndex(item => item.link_id == linkItem.link_id);
                                            if (index != -1) {
                                                tmpList[index].link_type = value;
                                                setLinkList(tmpList);
                                            }
                                        }}
                                            style={{ width: "60px" }}>
                                            <Select.Option value={EXTRA_LINK_ARTICLE}>文章</Select.Option>
                                            <Select.Option value={EXTRA_LINK_VIDEO}>视频</Select.Option>
                                            <Select.Option value={EXTRA_LINK_TEST}>评估</Select.Option>
                                            <Select.Option value={EXTRA_LINK_COURSE}>课程</Select.Option>
                                            <Select.Option value={EXTRA_LINK_WEBSITE}>网站</Select.Option>
                                        </Select>
                                    </Form.Item>
                                    <Form.Item label="名称">
                                        <Input style={{ width: "80px" }} value={linkItem.link_title} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = linkList.slice();
                                            const index = tmpList.findIndex(item => item.link_id == linkItem.link_id);
                                            if (index != -1) {
                                                tmpList[index].link_title = e.target.value.trim();
                                                setLinkList(tmpList);
                                            }
                                        }} />
                                    </Form.Item>
                                    <Form.Item label="网址">
                                        <Input style={{ width: "230px" }} value={linkItem.link_url} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = linkList.slice();
                                            const index = tmpList.findIndex(item => item.link_id == linkItem.link_id);
                                            if (index != -1) {
                                                let url = e.target.value.trim();
                                                if (url.startsWith("https://") == false) {
                                                    url = "https://";
                                                }
                                                tmpList[index].link_url = url;
                                                setLinkList(tmpList);
                                            }
                                        }} />
                                    </Form.Item>
                                </Form>
                            </List.Item>
                        )} />
                </Card>
                <Form.Item style={{ display: "flex", justifyContent: "flex-end", marginRight: "20px" }}>
                    <Space>
                        <Button type="default" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            reset();
                        }}>重置</Button>
                        <Button type='primary' onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            updateNode(false);
                        }}>更新</Button>
                        <Button type='primary' onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            updateNode(true);
                        }}>更新并关闭</Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
};

export default observer(TopicNodeEditPanel);